﻿#include "Login.h"
#include <QGridLayout>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QDebug>

#include <QFile>
#include <QTextStream>
#include <QRegularExpression>

#include "User/UserManager.h"




Login::Login(QWidget* parent)
	:QWidget(parent)
{
	this->setWindowTitle("登录窗口");


	init();
}

void Login::init()
{
	layout();

	//test:
	usernameEdit->setText("1998017");
	passwordEdit->setText("1234567q");

	connect(loginBtn, &QPushButton::released, this, &Login::onLoginBtnReleased);
}

void Login::layout()
{
	usernameEdit = new QLineEdit;
	passwordEdit = new QLineEdit;
	loginBtn = new QPushButton("Login");
	infoLab = new QLabel;

	auto layout = new QFormLayout;
	layout->addRow("用户名", usernameEdit);
	layout->addRow("密码", passwordEdit);

	auto mlayout = new QVBoxLayout(this);
	mlayout->addLayout(layout);
	mlayout->addWidget(loginBtn);
	mlayout->addWidget(infoLab);


}


void Login::onLoginBtnReleased()
{
	//qInfo() << 1;



	//获取账号和密码：
	auto username = usernameEdit->text();
	auto password = passwordEdit->text();



	//进行验证：
	QFile file("./data/user.txt");
	if (!file.open(QIODevice::ReadOnly))
	{
		qWarning("打开user.txt失败");
		return;
	}


	QTextStream stream(&file);
	stream.readLine();		//去掉并删除

	while (!stream.atEnd())
	{
		//读取user.txt内的数据：
		auto userList = stream.readLine().split(QRegularExpression("[ \t]+"));

		//创建UserManager	对象，用来保存和管理user.txt的数据：
#if 0
		UserManager userManager;
		userManager.addUser(new User(userList[0], userList[1], User::UserType(userList[2].toInt())));
		//显示打印下Users里的容器内容数据：
		for (auto user : userManager)
		{
			qInfo() << *user;
		}
		//只能有一个UserManager，	所以这个类需要是单例模式；所以不能这样初始化对象，要使用单例模式；

#else
		UserManager::instance()->addUser(new User(userList[0], userList[1], User::UserType(userList[2].toInt())));

#endif

		//qInfo() << userList;	//打印user用户列表 test

		if (userList[0] == username && userList[1] == password)
		{
			qInfo() << "登录成功";

			this->hide();
			m_mainwindow = new MainWindow;
			m_mainwindow->show();
			

			break;

		}

	}
	//显示打印下Users里的容器内容数据：
	//for (auto user : *UserManager::instance())
	//{
	//	qInfo() << *user;
	//}
}